package org.upt.dcda.presentation;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Arrays;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.upt.dcda.BookManagerBeanRemote;
import org.upt.dcda.OrderItem;
import org.upt.dcda.OrderManagerBeanRemote;
import org.upt.dcda.db.UserEntity;

import com.google.gson.Gson;

/**
 * Servlet implementation class PlaceOrderServlet
 */
// @WebServlet("/PlaceOrderServlet")
public class PlaceOrderServlet extends HttpServlet
{

	private static final long		serialVersionUID	= 1L;

	@EJB
	private OrderManagerBeanRemote	orderManagerBean;

	@EJB
	private BookManagerBeanRemote	bookManagerBean;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PlaceOrderServlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		// TODO Auto-generated method stub

		try
		{
			Cookie cookie = getCookie("basket", request);
			Gson gson = new Gson();
			OrderItem[] orderItems = null;

			orderItems = gson.fromJson(
					URLDecoder.decode(cookie.getValue(), "UTF-8"),
					OrderItem[].class);

			getServletContext().log(
					"OrderItems: " + Arrays.toString(orderItems));

			UserEntity user = (UserEntity) request.getSession().getAttribute(
					SessionAttributes.USER);
			orderManagerBean.placeOrder(user, orderItems);

			// delete cookies
			cookie.setMaxAge(0);
			response.addCookie(cookie);

			// redirect to browse page
			response.sendRedirect(response.encodeRedirectURL(request
					.getContextPath() + "/browse.html"));
		}
		catch (Throwable t)
		{
			getServletContext().log("Caught Exception: " + t, t);
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
					t.toString());
		}

	}

	private Cookie getCookie(String name, HttpServletRequest request)
	{
		Cookie[] cookies = request.getCookies();
		if (cookies != null)
		{
			for (int i = 0; i < cookies.length; i++)
			{
				if (cookies[i].getName().equals(name))
				{
					return cookies[i];
				}
			}
		}
		return null;
	}
}
